﻿define(function (require, exports, module) {
    var myPub = require('./public');

    var oBody = $('body');
    var oFooter = $(".js_footer"); 					// 底部
    var oReasonList = $('.js_reasonList');          // 售后原因选择
    var oSubmitApply = $('.js_submitApply');        // 提交申请

    var $applyCause = $('#applyCause');             // 申请原因

    var oShadow = $('.js_shadow');                  // 阴影加载图

    var oApplyReasons = $('.js_ApplyReasons');		// 申请原因点击
    var oReasonsResult = $('.js_reasonsResult');	// 申请原因选择的结果
    var oCloseBtn = $('.js_closeBtn');				// 弹框关闭按钮
    var oSeletBtn = $('.js_seletBtn');				// 弹框关闭按钮
    var bSideOff = true;							// 阻止多次点击开关
    var oReasonSide = $('.js_reasonSide');	        // 弹框

    var oPayMentReasons = $('.js_payMentReasons');  // 赔付金额选择
    var oPayMentSide = $('.js_payMentSide');        // 赔付金额弹层
    var oPayMentList = $('.js_payMentList');        // 赔付金额价格选择
    var oPayMentResult = $('.js_payMentResult');
    var oLoseMoney = $('.js_loseMoney');

    var oLoseMoneyInput = $('.js_loseMoneyInput');

    //解决申请赔付页面输入bug的代码 start
    var timerId = null; //定时器定义



    var oPayCaption = $('.js_payCaption');
    var oPayCaptionSide = $('.js_payCaptionSide');

    var oSeletSide = $('.js_seletSide'); 				// 弹层
    var moveHeight = oSeletSide.outerHeight(true);    	// 弹框高度

    oSeletSide.css({'bottom': -moveHeight, 'opacity': 1});


    var oAmountBox = $('.js_amountBox');                    // 数量框
    var oSumNum = $('.js_sumNum');                          // 总数
    var oHandBtn = oAmountBox.find('.js_handBtn');
    var maxNum = quantity;
    var minNum = 1;
    var aPrice = [];
    if(maxNum == 0) maxNum = 1;
    // 记录旧的数据
    recordPrice();


    // 提交售后申请
    oSubmitApply.hammer().on('tap', function () {
        if (validate()) {

            if($("#refundAmount").val()>=200 || oSumNum.val()>2 ){
                myPub.askLayer('您好，由于您申请的闪赔金额或份数过多，您将无法使用“闪赔”服务，如继续申请将转为人工审核流程！', function () {
                $.ajax({
                    url: "/shop/workOrder/applyAfterSales",
                    type: "POST",
                    data: $("#apply-form").serialize(),
                    dataType: 'json',
                    success: function (data) {
                        $('.layermcont').find('p').remove();    // 移除图片加载文字
                        myPub.LayerCloseAll();
                        if (data.status == 'success') {
                            myPub.TipLayerEnd(data.message, '', function () {
                                window.location.href = "/shop/pay/order_view?orderSn=" + data.orderSn;
                            }, '');
                        } else {
                            myPub.TipLayer(data.message);
                        }
                    },
                    error: function () {

                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        XMLHttpRequest = null;
                        // oShadow.hide().find('.js_loadPng').removeClass('myRotateRefresh');
                        oFooter.hide()
                    }
                });
                }, function () {
                 myPub.LayerCloseAll();
                 }, 'no', function () {
                 $('.layermbox0 .layermchild').css({
                 'max-width': '80%'
                 }).find('.layermcont').css({
                 'text-align': 'left'
                 })
                 }, ['确定', '取消']);

            }else{
                // sCont,yesFn, noFn,sTit,callBack, aBtnName
                myPub.askLayer('请确保您提交的理赔申请与实际相符，否则将影响您的闪赔权益', function () {
                    $.ajax({
                        url: "/shop/workOrder/applyPreRefund",
                        type: "POST",
                        data: $("#apply-form").serialize(),
                        dataType: 'json',
                        success: function (data) {
                            $('.layermcont').find('p').remove();    // 移除图片加载文字
                            myPub.LayerCloseAll();
                            if (data.status == 'success') {
                                myPub.TipLayerEnd(data.message, '', function () {
                                    window.location.href = "/shop/pay/order_view?orderSn=" + data.orderSn;
                                }, '');
                            } else {
                                myPub.TipLayer(data.message);
                            }
                        },
                        error: function () {

                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            XMLHttpRequest = null;
                            // oShadow.hide().find('.js_loadPng').removeClass('myRotateRefresh');
                            oFooter.hide()
                        }
                    });
                }, function () {
                    myPub.LayerCloseAll();
                }, 'no', function () {
                    $('.layermbox0 .layermchild').css({
                        'max-width': '80%'
                    }).find('.layermcont').css({
                        'text-align': 'left'
                    })
                }, ['确认提交', '我再想想']);
            }

        } else {
            // console.info('validate failed');
        }
    });

    // 售后原因选择
    oReasonList.find('li').hammer().on('tap', function () {
        oReasonList.find('li').removeClass('active');
        $(this).addClass('active');
        oReasonsResult.text($(this).find('span').eq(0).text()).removeClass('color_gray_D3');
        $applyCause.val($(this).find('span').eq(0).text());

        oSeletSide.stop().animate({bottom: -moveHeight}, 300, function () {
            oSeletSide.hide();
            oShadow.hide();
            $('html').removeClass('bodyHeight100');
            bSideOff = true
        });
    });

    // 申请原因弹框显示和消失
    oApplyReasons.hammer().on('tap', function () {
        if (!bSideOff) return;
        bSideOff = false;

        oReasonSide.show().stop().animate({'bottom': 0}, 300, function () {
            oShadow.show();
            $('html').addClass('bodyHeight100');
            bSideOff = true
        });

    });

    // 申请赔付金额弹框
    oPayMentReasons.hammer().on('tap', function () {
        if (!bSideOff) return;
        bSideOff = false;

        oPayMentSide.show().stop().animate({'bottom': 0}, 300, function () {
            oShadow.show();
            $('html').addClass('bodyHeight100');
            bSideOff = true
        });

    });

    // 当input输入时聚焦事件
    oLoseMoneyInput.on('focus', function () {
        myPub.setFocusBodyScrollTop(timerId);
    });


    oLoseMoneyInput.on('blur', function () {
        //离开焦点时要清除定时器
        if (timerId) {
            clearInterval(timerId);
            timerId = null;
        }
    });

    oLoseMoneyInput.on('input propertychange',function(e) {
        oPayMentList.find('li').removeClass('active');
    });

    // 解决申请赔付页面输入bug的代码 end

    // 赔付金额选择
    oPayMentList.find('li').hammer().on('tap', function () {
        if($(this).hasClass('active')) {
            oPayMentList.find('li').removeClass('active');
            oPayMentResult.text('请选择申请闪赔金额').addClass('color_gray_D3');
            oLoseMoneyInput.val('');
            $('#refundAmount').val('');
        }
        else {
            oPayMentList.find('li').removeClass('active');
            $(this).addClass('active');
            var result = $(this).find('em').text() * 1;
            result = result.toFixed(2);
            oPayMentResult.text( result ).removeClass('color_gray_D3');
            oLoseMoneyInput.val(result);
            $('#refundAmount').val(result);
        }

    });

    oLoseMoney.find('button').on('click', function () {
        checkMoney(oLoseMoneyInput, function () {
            myPub.TipLayer("请输入数字,支持两位有效小数！");
            $('#refundAmount').val('');
        }, function () {
            myPub.TipLayer("请输入数字,支持两位有效小数！");
            oLoseMoneyInput.val('');
            $('#refundAmount').val('');
        }, function () {
            var _money = oLoseMoneyInput.val();
            oPayMentResult.text(_money).removeClass('color_gray_D3');
            $('#refundAmount').val(_money);
            CloseSide();
        });
    });


    // 理赔流程说明
    oPayCaption.hammer().on('tap', function () {
        if (!bSideOff) return;
        bSideOff = false;

        oPayCaptionSide.show().stop().animate({'bottom': 0}, 300, function () {
            oShadow.show();
            $('html').addClass('bodyHeight100');
            bSideOff = true
        });
    });


    // 申请原因确定
    oSeletBtn.hammer().on('tap', function () {
        oReasonsResult.text(oReasonList.find('li.active').eq(0).text()).removeClass('color_gray_D3');
        $applyCause.val(oReasonList.find('li.active').eq(0).text());
        CloseSide();
        myPub.HamstopPropaga();
    });

    // 关闭按钮
    oCloseBtn.hammer().on('tap', function () {
        CloseSide();
        myPub.HamstopPropaga();
    });

    // 阴影关闭
    oShadow.hammer().on('tap', function () {
        // 隐藏服务
        CloseSide();
        myPub.HamstopPropaga();
    });



    // 当input输入时聚焦事件
    oSumNum.on('focus', function () {
        myPub.setFocusBodyScrollTop(timerId);
    });

    oSumNum.on('blur', function () {
        //离开焦点时要清除定时器
        if (timerId) {
            clearInterval(timerId);
            timerId = null;
        }
    });

    oSumNum.on('input propertychange',function(e) {
        myPub.ValiNum(oSumNum, function() {
            myPub.TipLayer('输入正确数字');
            oSumNum.val(minNum);
            $("#quantity").val(minNum);
            oHandBtn.eq(0).addClass('active');
        },function() {
            oHandBtn.removeClass('active');
            var _iNow = oSumNum.prop('value')*1;
            // 设置最大值会导致底部上移
            if(_iNow > maxNum) {
                _iNow = maxNum;
                oSumNum.val(_iNow);
                myPub.TipLayer("最多只能"+maxNum);
                oHandBtn.eq(1).addClass('active');
            }
            if(_iNow < minNum) {
                _iNow = minNum;
                oSumNum.val(_iNow);
                oHandBtn.eq(0).addClass('active');
                myPub.TipLayer("不能再少了");
            }
            countprice(_iNow);
            $("#quantity").val(_iNow);
        });
    });


    oHandBtn.hammer().on('tap',function(e) {
        // 库存
        var index = oHandBtn.index(this);
        var _iNow = oSumNum.val();
        oSumNum.blur();
        oHandBtn.removeClass('active');
        switch(index) {
            //减少
            case 0:
                if(_iNow <= minNum) {
                    oHandBtn.eq(index).addClass('active')
                    _iNow = minNum;
                    myPub.TipLayer("不能再少了");
                }
                else {
                    _iNow--;
                }
                break;
            //增加
            case 1:
                if(_iNow > maxNum-1) {
                    oHandBtn.eq(index).addClass('active')
                    _iNow = maxNum;
                    myPub.TipLayer("最多只能" + maxNum);
                }
                else {
                    _iNow++;
                }
                break;
        }
        countprice(_iNow);
        oSumNum.val(_iNow);
        $("#quantity").val(_iNow);
    });

    // 获取1份价格
    function recordPrice() {
        oPayMentList.find('li').each(function (i) {
            var _val = $(this).find('em').text() * 1;
            aPrice.push(_val);
        })
    }

    // 设置价格
    function countprice(iNow) {
        oPayMentList.find('li').each(function (i) {
            var _val = aPrice[i] * iNow;
            $(this).find('em').text( _val.toFixed(2) );

            if( $(this).hasClass('active') ) {
                oLoseMoneyInput.val(_val.toFixed(2));
            }
        })

    }

    // 关闭弹层
    function CloseSide() {
        oSeletSide.stop().animate({bottom: -moveHeight}, 300, function () {
            oSeletSide.hide();
            oShadow.hide();
            oLoseMoneyInput.blur();
            oSumNum.blur();
            $('html').removeClass('bodyHeight100');
            bSideOff = true
        });
    }

    function validate() {
        var applyCause = $('#applyCause').val(),
            description = $("#description").val(),
            voucher = $("#voucher").val();

        if (!applyCause) {
            myPub.TipLayer("请选择申请原因");
            return false;
        }

        if (!description) {
            myPub.TipLayer("请输入问题描述");
            return false;
        }

        if (!voucher) {
            myPub.TipLayer("请上传至少一张凭证");
            return false;
        }

        if (!checkRefund()) {
            return false;
        }

        return true;
    }

    function checkRefund() {
        var tmpv = $("#refundAmount").val();
        var maxMoney = $('#maxMoney').val();

        if (!/^[0-9]+(.[0-9]{0,2})?$/.test(tmpv)) {
            myPub.TipLayer("请选择赔付金额,支持两位有效小数");
            return false;
        }
        if (parseFloat(maxMoney) < parseFloat(tmpv)) {
            myPub.TipLayer("赔付金额需要不大于" + maxMoney);
            return false;
        }
        if (parseFloat(tmpv) <= parseFloat(0)) {
            myPub.TipLayer("赔付金额需要大于" + 0);
            return false;
        }
        return true;
    }

    // 检测金额
    function checkMoney(obj, fn1, fn2, fn3) {
        var tmpv = obj.val();
        var reg = /^[0-9]+(.[0-9]{0,2})?$/;   //验证用户名

        if (tmpv == '') {
            fn1();
        }
        if (!reg.test(tmpv)) {
            if (tmpv == '') return;
            fn2();
        }
        else {
            fn3();
        }
    }


});



